package com.zhaoxi.project.crm.utils;

import com.alibaba.fastjson2.JSONObject;
import com.zhaoxi.common.utils.DateUtils;
import com.zhaoxi.common.utils.StringUtils;
import com.zhaoxi.project.crm.enums.GenderStatus;
import com.zhaoxi.project.crm.enums.ResumeSourcesEnum;
import com.zhaoxi.project.md.domain.MdPartner;
import org.apache.pdfbox.io.RandomAccessRead;
import org.apache.pdfbox.io.RandomAccessReadBuffer;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.ParseException;
import java.util.*;

public class ResumeUtil {

    private static final Logger logger = LoggerFactory.getLogger(ResumeUtil.class);


    public static String getXinAnRenCai(InputStream inputStream){
        String s = readPDF(inputStream);
        MdPartner jsonObject = new MdPartner();
        jsonObject.setResumeText(s);
        String[] pdfTextArray = s.split("\n");
        for (int i = 0; i < pdfTextArray.length; i++) {
            String row = pdfTextArray[i];
            if (row.contains("应聘职位")) {
                String[] s1 = row.split("应聘职位：");
                jsonObject.setName(s1[0].trim());
//                jsonObject.setPositionApplied(s1[1].trim());
            } else if (row.contains("电话：") || row.contains("电话:")) {
                jsonObject.setMobile(row.split("：")[1].substring(0,11));
            }else if (row.contains("学历")){
//                jsonObject.setEducation(row.split("：")[1].substring(0,2));
            }else if (i==1){
                jsonObject.setSex(row.split("|")[0].trim().equals("男") ? "0":"1");
            }
        }
        jsonObject.setSource(String.valueOf(ResumeSourcesEnum.XIN_AN.getType()));
        return JSONObject.toJSONString(jsonObject);
    }



    public static String getZhiLian(InputStream inputStream) {
        String s = readPDF(inputStream);
        MdPartner jsonObject = new MdPartner();
        jsonObject.setResumeText(s);
        String gzjl = "";
        // String xmjy = "";
        // String[] pdfTextArray = s.replace(" ", "").replace("\r", "").split("\n");
        String[] pdfTextArray = s.split("\n");
        List<String> headList = new ArrayList<>(10);
        for (int i = 3; i < pdfTextArray.length; i++) {
            String row = pdfTextArray[i];
            if (row.contains("点击此处联系")) {
                String[] s1 = row.split("点击此处联系");
                jsonObject.setName(s1[0].trim());
//			} else if (row.contains("应聘职位：")) {
//				jsonObject.setPositionApplied(row.split("：")[1].trim());
            } else if (row.contains("手机：")) {
                jsonObject.setMobile(row.split("：")[1].trim());
            }else if (row.contains("基本信息")) {
				String[] infos = pdfTextArray[i + 1].split("｜");
				jsonObject.setSex(changeGnder(infos[0].trim()));
//                System.out.print(infos[0].trim());
//				int age = Integer.parseInt(infos[1].substring(0, infos[1].indexOf("岁")).trim());
//				int year = LocalDate.now().getYear() - age;
//				jsonObject.setBirthday(DateUtils.parseDate(String.valueOf(year) + "-01-01"));
////				jsonObject.setAge(Integer.parseInt(infos[1].substring(0, infos[1].indexOf("岁"))));
            } else if (row.contains("20") && row.contains("/⽉")) {
                gzjl += pdfTextArray[i - 1] + ",";
            }
            if (row.startsWith(" ")) {
                headList.add(row.trim());
            }
        }
        System.out.println(headList);
        if (headList.contains("教育经历")) {

            int jv_index = headList.indexOf("教育经历");
            String jiaoyv = "";
            if (jv_index != headList.size() - 1) {
                String s1 = headList.get(jv_index + 1);
                jiaoyv = s.substring(s.indexOf("教育经历"), s.indexOf(s1));
            } else {
                jiaoyv = s.substring(s.indexOf("教育经历"));
            }

            String[] jiaoyvList = jiaoyv.split("\n");
            Map<String, String> map = new HashMap<>(3);
            map.put("time", "0");
            for (int a = 0; a < jiaoyvList.length; a++) {
                if (jiaoyvList[a].contains("20")) {
                    int last = jiaoyvList[a].lastIndexOf(".");
                    int year = Integer.parseInt(jiaoyvList[a].substring(last - 4, last));
                    String month = jiaoyvList[a].substring(last + 1, last + 3);
                    if (Integer.parseInt(map.get("time")) < year) {
                        map.put("time", String.valueOf(year));
                        map.put("school", jiaoyvList[a - 1].split(" ")[0]);
                        map.put("zhuanye", jiaoyvList[a - 1].split(" ")[1].replace("\r", ""));
                        map.put("month", month);
                        map.put("xueli", jiaoyvList[a].split(" ")[3]);
                    }
                }
            }
//            jsonObject.setGraduationSchool(map.get("school"));
//            jsonObject.setMajor(map.get("zhuanye"));
//            jsonObject.setEducation(map.get("xueli"));
//            jsonObject.setGraduationTime(DateUtils.parseDate(map.get("time") + "-" + map.get("month") + "-01"));
        }

        jsonObject.setSource(String.valueOf(ResumeSourcesEnum.ZHI_LIAN.getType()));
        return JSONObject.toJSONString(jsonObject);
    }


    public static String getBossZhiPin (InputStream inputStream){
        String s = readPDF(inputStream);
        MdPartner jsonObject = new MdPartner();
        jsonObject.setResumeText(s);
        String[] pdfTextArray = s.split("\n");
        String gzjl = "";
        List<String> headList = new ArrayList<>();
        try {
            for (int i = 0; i < pdfTextArray.length; i++) {
                String row = pdfTextArray[i];
                System.out.println(row);
                if (i == 1) {
                    String[] s1 = row.split("\n");
                    jsonObject.setName(s1[0].trim());
                } else if (i == 2) {
                    String[] s1 = row.split("[\\|]");
                    for (String value : s1) {
                        if (value.length() == 11) {
                            jsonObject.setMobile(s1[0].trim());
                        }
//						if (value.contains("男")) {
//							jsonObject.setSex("0");
//						}if (value.contains("女")) {
//							jsonObject.setSex("1");
//						}
                    }

                } else if (row.contains("⼿机：")) {
                    jsonObject.setMobile(row.split("：")[1].trim());
                }  else if (row.contains("20") && row.contains("/⽉")) {
                    gzjl += pdfTextArray[i - 1] + ",";
                }
                if (row.startsWith(" ")) {
                    headList.add(row.trim());
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        jsonObject.setSource(String.valueOf(ResumeSourcesEnum.BOSS_ZHIPIN.getType()));
        System.out.println(jsonObject);
        return JSONObject.toJSONString(jsonObject);

    }

    public static byte[] getInputStream (MultipartFile fileObj) throws IOException {
        InputStream fis = fileObj.getInputStream();
        byte[] buffer = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int n;
        while ((n = fis.read(b)) != -1) {
            bos.write(b, 0, n);
        }
        fis.close();
        bos.close();
        buffer = bos.toByteArray();
        return buffer;
    }

    public static String get51 (InputStream inputStream){
        String s = read51(inputStream);
        MdPartner jsonObject = new MdPartner();
        jsonObject.setResumeText(s);
        String[] pdfTextArray = s.split("\n");
        // String[] pdfTextArray = s.replace(" ", "").replace("\r", "").split("\n");
        String gzjl = "";
        List<String> headList = new ArrayList<>();
        for (int i = 0; i < pdfTextArray.length; i++) {
            String row = pdfTextArray[i];
            logger.info("11111" + row);
            if (i == 4) {
                jsonObject.setName(row.split(" ")[0].trim());
            }
            if (row.length() == 4 && checkRealName(row)) {
                headList.add(row);
            }
            if (row.toLowerCase().contains("id:") && row.startsWith(" ")) {
                if (row.contains("标签")) {
                    jsonObject.setName(row.substring(0, row.indexOf("标签")).trim());
                } else {
                    jsonObject.setName(row.toLowerCase().substring(0, row.toLowerCase().indexOf("id")).trim());
                }
            } else if (row.trim().length() == 11 && row.trim().startsWith("1")) {
                jsonObject.setMobile(row.trim());
            } else if (row.contains("教育经历")) {
            }
        }
        jsonObject.setSource(String.valueOf(ResumeSourcesEnum.JOB_51.getType()));
        return JSONObject.toJSONString(jsonObject);
    }


    public static String get58 (InputStream inputStream){

        Date graduationTime = null;
        Workbook workbook = null;
        try {
            workbook = WorkbookFactory.create(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (workbook == null) {
            logger.warn("解析出现问题");
            return null;
        }
        Sheet sheet = workbook.getSheetAt(1);
        // 获取第一行数据
        int firstRowNum = sheet.getFirstRowNum();
        Row firstRow = sheet.getRow(firstRowNum);
        if (null == firstRow) {
            logger.warn("解析Excel失败，在第一行没有读取到任何数据！");
        }
        // 解析每一行的数据，构造数据对象
        int rowStart = firstRowNum;
        int rowEnd = sheet.getPhysicalNumberOfRows();
        int gzjl = 0;
        int jybj = 0;

        StringBuilder sb = new StringBuilder();
        String sex;
        MdPartner MdPartner = new MdPartner();
        MdPartner.setSource(String.valueOf(ResumeSourcesEnum.TONGCHENG_58.getType()));
        for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) {
            Row row = sheet.getRow(rowNum);
            if (null == row) {
                continue;
            }
            if (row.getCell(0).getStringCellValue().contains("工作经历")) {
                gzjl = rowNum;

            } else if (row.getCell(0).getStringCellValue().contains("手机")) {
                MdPartner.setMobile(row.getCell(1).getStringCellValue());
            } else if (row.getCell(0).getStringCellValue().contains("姓名")) {
                MdPartner.setName(row.getCell(1).getStringCellValue());
            } else if (row.getCell(0).getStringCellValue().contains("性别")) {
                if (row.getCell(1).getStringCellValue().trim().equals("男")) {
                    MdPartner.setSex("0");
                } else if (row.getCell(1).getStringCellValue().trim().equals("女")) {
                    MdPartner.setSex("1");
                } else {
                    MdPartner.setSex("2");
                }
            } else if (row.getCell(0).getStringCellValue().contains("出生年月")) {
                String year = row.getCell(1).getStringCellValue().substring(0, 4);

                MdPartner.setBirthday(DateUtils.parseDate(year + "-01-01"));
            } else if (row.getCell(0).getStringCellValue().contains("教育背景")) {
                jybj = rowNum;
                String stringCellValue = sheet.getRow(rowNum + 1).getCell(1).getStringCellValue();
                try {
                    graduationTime = DateUtils.parseDate(stringCellValue.split("毕业")[0], "yyyy/MM");
                } catch (ParseException e) {
                }
            }
            sb.append(row.getCell(0).getStringCellValue() + "," + row.getCell(1).getStringCellValue() + "\n");
        }

        String workEx = "";
        String projectEx = "";
        for (int rowNum = gzjl + 1; rowNum < jybj; rowNum++) {
            Row row = sheet.getRow(rowNum);
            String stringCellValue = row.getCell(1).getStringCellValue();
            if (stringCellValue.contains("20")) {
                workEx += stringCellValue.split("\\|")[1] + ",";
            }
            projectEx += stringCellValue + "\n";
        }

//        ExcelUtil<MdPartner> util = new ExcelUtil<>(MdPartner.class);
//        try {
//            List<MdPartner> resumeList = util.importExcelWorkBook("", workbook, 0);
//            if (!resumeList.isEmpty()) {
//                MdPartner = resumeList.get(0);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        // BdPartner.setContent(stringBuilder.toString());
        if (!StringUtils.isBlank(sb.toString())) {

            MdPartner.setResumeText(sb.toString());
        }

        return JSONObject.toJSONString(MdPartner);

    }

    private static String changeGnder (String value){
        return String.valueOf("男".equals(value.trim()) ? GenderStatus.MAN.ordinal() : GenderStatus.WOMAN.ordinal());
    }

    private static Boolean checkRealName (String realName){
        if (StringUtils.isEmpty(realName)) {
            return false;
        }

        char[] ch = realName.toCharArray();
        for (char c : ch) {
            if (c < 0x4E00 || c > 0x9FA5) {
                return false;
            }
        }
        return true;
    }

    public static String read51 (InputStream in){
        // File file = new File(fileName);
        // FileInputStream in = null;
        String result = "";
        try {
            // in = new FileInputStream(fileName);
            // 新建一个PDF解析器对象
            RandomAccessRead rw = new RandomAccessReadBuffer(in);
            PDFParser parser = new PDFParser(rw);
            // 对PDF文件进行解析
            PDDocument pdDocument = parser.parse();
            // // 获取解析后得到的PDF文档对象
            // PDDocument pdfdocument = parser.getPDDocument();
            // // 新建一个PDF文本剥离器
            PDFTextStripper stripper = new PDFTextStripper();
            stripper.setSortByPosition(false); //sort设置为true 则按照行进行读取，默认是false
            // // 从PDF文档对象中剥离文本
            result = stripper.getText(pdDocument);

        } catch (Exception e) {
            logger.warn("读取PDF文件失败！" + e);
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
        }
        return result;
    }

    public static String readPDF (InputStream in){
        // File file = new File(fileName);
        // FileInputStream in = null;
        String result = "";
        try {
            // in = new FileInputStream(fileName);
            // 新建一个PDF解析器对象
            RandomAccessRead rw = new RandomAccessReadBuffer(in);
            PDFParser parser = new PDFParser(rw);
            // 对PDF文件进行解析
            PDDocument pdDocument = parser.parse();
            // // 获取解析后得到的PDF文档对象
            // PDDocument pdfdocument = parser.getPDDocument();
            // // 新建一个PDF文本剥离器
            PDFTextStripper stripper = new PDFTextStripper();
            stripper.setSortByPosition(true); //sort设置为true 则按照行进行读取，默认是false
            // // 从PDF文档对象中剥离文本
            result = stripper.getText(pdDocument);
            String[] word = new String[]{"南京", "舟开", "舟", "合肥", "书心", "书" , "心"};
            for (int i = 0; i < word.length; i++) {
                if (result.contains(word[i])) {
                    result = result.replaceAll(word[i], "**");
                }
            }

        } catch (Exception e) {
            logger.warn("读取PDF文件失败！" + e);
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
        }
        return result;
    }

    public static void main (String[]args) throws FileNotFoundException {
        FileInputStream fileInputStream = new FileInputStream("C:\\Users\\Qbzzz\\OneDrive\\桌面\\51job_闫少伟_大数据开发工程师(524744897).pdf");
        String s = readPDF(fileInputStream);
        System.out.println(s);
    }
}
